/*
 * @Author: taosong 2289713738@qq.com
 * @Date: 2024-02-02 16:47:57
 * @LastEditors: taosong 2289713738@qq.com
 * @LastEditTime: 2024-03-20 10:35:47
 * @FilePath: \Song-ui\src\hooks\useClickOutside.ts
 * @Description: 
 * 
 * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved. 
 */
import { onMounted, onUnmounted } from "vue"
import { type Ref } from "vue"

const useClickOutside = (elementRef: Ref<undefined | HTMLElement>, callback: (e: MouseEvent) => void) => {
  const handler = (e: MouseEvent) => {
    if (elementRef.value && e.target) {
      // 类型收窄
      if (!elementRef.value.contains(e.target as HTMLElement)) {
        callback(e)
      }
    }
  }

  onMounted(() => {
    document.addEventListener('click', handler)
  })

  onUnmounted(() => {
    document.removeEventListener('click', handler)
  })
}

export default useClickOutside